<template>
    <div>
      <h2>个人资料</h2>
      <el-form :model="userInfo" label-width="120px">
        <div class="form-row">
          <el-form-item label="用户名">
            <el-input v-model="userInfo.username" />
          </el-form-item>
          <el-form-item label="角色">
            <el-input v-model="roleLabel" disabled />
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="手机号">
            <el-input v-model="userInfo.userphone" />
          </el-form-item>
          <el-form-item label="性别">
            <el-input v-model="userInfo.sex" />
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="地址">
            <el-input v-model="userInfo.useraddress" />
          </el-form-item>
          <el-form-item label="别名">
            <el-input v-model="userInfo.nickname" />
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="注册时间">
            <el-input v-model="formattedCreateTime" disabled />
          </el-form-item>
          <el-form-item label="最后更新时间">
            <el-input v-model="formattedUpdateTime" disabled />
          </el-form-item>
        </div>
  
        <div class="avatar-section">
          <h3>用户头像</h3>
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :on-change="handleChange"
            :before-upload="beforeUpload"
          >
            <img
              v-if="previewImage"
              :src="previewImage"
              class="avatar"
              alt="头像"
            />
            <el-button v-else style="margin-top: 34px;margin-left: 5px;">上传头像</el-button>
          </el-upload>
        </div>
  
        <el-button type="primary" @click="submitUpdate" style="margin-top: 20px;margin-left: 40px;">确认修改</el-button>
      </el-form>
    </div>
  </template>
  
  <script>
  import { userInfoService, updateUserService } from '@/api/user';
  
  export default {
    data() {
      return {
        userInfo: {
          id: null,  
          username: '',
          userphone: '',
          sex: null,
          useraddress: null,
          nickname: null,
          role: 'USER',
          createTime: '',
          updateTime: '',
          userphoto: ''  
        },
        previewImage: '',
        selectedFile: null,
      }
    },
    computed: {
      roleLabel() {
        return this.userInfo.role === 'ADMIN' ? '管理员' : '用户';
      },
      formattedCreateTime() {
        return new Date(this.userInfo.createTime).toLocaleString();
      },
      formattedUpdateTime() {
        return new Date(this.userInfo.updateTime).toLocaleString();
      }
    },
    created() {
      this.fetchUserInfo();
    },
    methods: {
      async fetchUserInfo() {
        const response = await userInfoService();
        this.userInfo = response.data;
      },
      async submitUpdate() {
        const userUpdateData = {
            id: this.userInfo.id,  
            username: this.userInfo.username,
            nickname: this.userInfo.nickname || null, // 你可以选择将它留空或设置为 null
            userphone: this.userInfo.userphone,
            sex: this.userInfo.sex || null, // 同样的处理
            useraddress: this.userInfo.useraddress || null,
            idCard: this.userInfo.idCard || null,  // 确保 idCard 可用
            password: this.userInfo.password || null, // 确保密码可用，如果是允许用户更新密码的话
            role: this.userInfo.role || 'USER', // 默认角色使用 'USER'
            createTime: this.userInfo.createTime || new Date().toISOString(), // 创建时间
            updateTime: new Date().toISOString(), // 更新为当前时间
            userphoto: '', // 如果需要，可以保留或设置为空 
        };

        console.log('请求数据:', userUpdateData);

        try {
            await updateUserService(userUpdateData);
            this.$message.success('个人信息更新成功');
        } catch (error) {
            console.error('更新失败:', error);
            this.$message.error('更新信息失败：' + error.message);
        }
        },
      handleChange(file) {
        this.selectedFile = file.raw;
        const reader = new FileReader();
        reader.readAsDataURL(file.raw);
        reader.onload = () => {
          this.previewImage = reader.result;
        };
      },
      beforeUpload(file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt5M = file.size / 1024 / 1024 < 5;
  
        if (!isJpgOrPng) {
          this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
        }
        if (!isLt5M) {
          this.$message.error('上传头像图片大小不能超过 5MB!');
        }
  
        return isJpgOrPng && isLt5M;
      }
    }
  }
  </script>
  
  <style scoped>
  .form-row {
    display: flex;
  }
  .form-row .el-form-item {
    flex: 1;
    margin-right: 20px;
  }
  .form-row .el-form-item:last-child {
    margin-right: 0;
  }
  .avatar-section {
    margin-top: 20px;
    margin-bottom: 20px;
    text-align: left;
    margin-left: 50px;
  }
  .avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    margin-bottom: 10px;
  }
  .avatar-uploader {
    display: inline-block;
    width: 100px; /* 固定宽度 */
    height: 100px; /* 固定高度 */
    border: 1px dashed #dcdfe6; /* 头像上传框 */
    border-radius: 50%; /* 圆形 */
    overflow: hidden; /* 避免内容溢出 */
    position: relative;
    cursor: pointer;
  }
  </style>
  